import { Modal, Form, Input, DatePicker, message, Select, Button, Space } from 'antd'
import styles from './style.less'
const FormItem = Form.Item;
import EnterpriseUserSelect from '@/components/EnterpriseUserSelect';
import { PROJECT_QA_CASE_SCENE } from '@/consts/project'
import { connect } from 'umi';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons'
import ArrayUtils from '@/utils/ArrayUtils';
import { save, update } from '@/services/project/qaCase'
import { useEffect } from 'react';
import IdUtils from '@/utils/IdUtils'
import { useState } from 'react';


const QACaseAddModal = (props) => {

    const {
        projectId,
        visible,
        onCancel,
        onSaveSuccess,
        qaDetail,
        defaultValue
    } = props;


    const [form] = Form.useForm();
    const [formInitValues,setFormInitValues] = useState();
    const [saveLoading,setSaveLoading] = useState();

    useEffect(() => {
        setFormInitValues(defaultValue)
    }, [defaultValue])

    useEffect(() => {
        form.resetFields()
    }, [formInitValues])

    const saveQACase = async () => {
        const values = await form.validateFields()
        console.log(values)
        let stepsExpect = []
        if (values.stepsExpect) {
            stepsExpect = values.stepsExpect.map((item) => {
                if (item.id) {
                    return item;
                }
                return {
                    ...item,
                    id:IdUtils.uuid()
                }
            })
        }
        const data = {
            ...values,
            stepsExpect
        }
        setSaveLoading(true)
        if (defaultValue && defaultValue.id) {
            update(projectId, qaDetail.id, defaultValue.id, data)
                .then(result => {
                    if (result.success) {
                        message.success("保存成功！")
                        onSaveSuccess()
                        form.resetFields()
                        setSaveLoading(false)

                    }
                })

        } else {
            save(projectId, qaDetail.id, data)
                .then(result => {
                    if (result.success) {
                        message.success("保存成功！")
                        onSaveSuccess()
                        form.resetFields()
                        setSaveLoading(false)
                    }
                })
        }
    }

    return (<Modal
        visible={visible}
        closable
        title={"新增用例"}
        onCancel={() => {
            if (onCancel) {
                form.resetFields()
                onCancel()
            }
        }}
        onOk={() => {
            saveQACase();
        }}
        width="60%"
        destroyOnClose
        loading={saveLoading}
        okText={"确认"}
        cancelText={"取消"}
    >
        <Form
            form={form}
            labelAlign="right"
            labelCol={{ span: 2 }}
            initialValues={formInitValues}
        >
            <FormItem
                label={"名称"}
                name="name"
                rules={[
                    {
                        required: true,
                        message: "请输入名称",
                    },
                ]}
            >
                <Input placeholder={"请输入名称"} maxLength={20} ></Input>
            </FormItem>
            <FormItem
                label={"模块"}
                name="moduleName"
            >
                <Select placeholder={"请选择模块"}>
                    {qaDetail && qaDetail.modules &&
                        qaDetail.modules.map((item => <Option value={`${item.name}`} key={`${item.name}`}>{item.name}</Option>))
                    }
                </Select>
            </FormItem>
            <Form.Item className={styles.formItemGroup} >
                <FormItem
                    label={"负责人"}
                    name="userId"
                    style={{ width: 'calc(50% )', marginRight: '8px' }}
                    rules={[
                        {
                            required: true,
                            message: "请选择负责人",
                        },
                    ]}
                >
                    <EnterpriseUserSelect projectId={projectId} ></EnterpriseUserSelect>
                </FormItem>
                <FormItem
                    label={"用例类型"}
                    style={{ width: 'calc(50% )', marginRight: '8px' }}
                    name="scene"
                >
                    <Select placeholder={"请选择测试用例类型"} maxLength={20} >
                        {ArrayUtils.jsonToArray(PROJECT_QA_CASE_SCENE).map(item => <Option value={`${item.key}`} key={`${item.key}`}>{item.value.name}</Option>)}
                    </Select>
                </FormItem>

            </Form.Item>


            <FormItem label="步骤期望">
                <Form.List name="stepsExpect" >
                    {(fields, { add, remove }) => (
                        <>
                            {fields.map(({ key, name, fieldKey, ...restField }) => (
                                <div key={key} style={{ display: "flex", alignItems: "center", padding: "4px", width: "100%" }}>
                                    <FormItem
                                        {...restField}
                                        style={{ marginBottom: 0, marginRight: "8px", width: '100%' }}
                                        name={[name, 'step']}
                                        fieldKey={[fieldKey, 'step']}
                                        rules={[{ required: true, message: '请输入步骤' }]}
                                    >
                                        <Input placeholder="步骤" maxLength={40} />
                                    </FormItem>
                                    <FormItem
                                        {...restField}
                                        style={{ marginBottom: 0, marginRight: "8px", width: '100%' }}
                                        name={[name, 'expect']}
                                        fieldKey={[fieldKey, 'expect']}
                                        rules={[{ required: true, message: '请输入期望' }]}
                                    >
                                        <Input placeholder="期望" maxLength={40} />
                                    </FormItem>
                                    <MinusCircleOutlined onClick={() => remove(name)} />
                                </div>
                                // <Space key={key} align="center" style={{ padding: "4px",width:"100%" }}>

                                // </Space>
                            ))}
                            <FormItem style={{ padding: "4px" }}>
                                <Button type="dashed" onClick={() => {
                                    if (fields && fields.length > 10) {
                                        message.error("最多只能添加10组")
                                        return
                                    }
                                    add()
                                }} block style={{ width: "240px" }} icon={<PlusOutlined />}>新增 </Button>
                            </FormItem>
                        </>
                    )}
                </Form.List>
            </FormItem>
        </Form>
    </Modal>)
}

export default connect(({ qa, loading }) => ({

}))(QACaseAddModal);
